﻿#include "osm_frame_widget.h"
#include <QApplication>
#include <QLibraryInfo>
#include <QTranslator>
#include <QMap>
#include <QFile>
#include <QVariantMap>
#include "listen_thread.h"
#include "interface_utils.h"
#include "tb_interface/cmdlineparser.h"
#include "tb_interface/tb_interface.h"
const bool TASKBUSDBG = false;
using namespace TASKBUS;
int main(int argc, char *argv[])
{
	QApplication app(argc, argv);
	//taskBus init
	init_client();
	cmdlineParser args;

	//Options
	bool stdio = false , stdio_box = true;
	for (int i=1;i<argc;++i)
	{
		if (strstr(argv[i],"-stdio_box=off"))
		{
			stdio_box = false;
			stdio = false;
		}
		else if (strstr(argv[i],"-stdio=on"))
			stdio = true;
	}

	//Debug
	if (TASKBUSDBG)
	{
		auto cmdline = TASKBUS::debug("d:/log/pid2837",0,0);
		args.parser(cmdline);
	}
	else
		args.parser(argc,argv);

	int ret = 0;
	//Arg--information参数,打印自己的功能定义字符串。
	if (args.contains("information"))
	{
		QFile fp(":/interface.json");
		if (fp.open(QIODevice::ReadOnly))
		{
			QByteArray arr = fp.readAll();
			arr.push_back('\0');
			puts(arr.constData());
			fflush(stdout);
		}
		return ret;
	}


	QTranslator qtTranslator;
#if QT_VERSION>=0x060000
	if (qtTranslator.load("qt_" + QLocale::system().name(),
					  QLibraryInfo::path(QLibraryInfo::TranslationsPath)))
		app.installTranslator(&qtTranslator);
#else
	if (qtTranslator.load("qt_" + QLocale::system().name(),
					  QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
		app.installTranslator(&qtTranslator);
#endif


	QTranslator appTranslator;
	QString strTransLocalFile =
			QCoreApplication::applicationDirPath()+"/" +
			QCoreApplication::applicationName()+"_"+
			QLocale::system().name()+".qm";
	bool loadRes = false;
	if (false==appTranslator.load(strTransLocalFile ))
		loadRes = true;
	else if (false==app.installTranslator(&appTranslator))
		loadRes = true;

	if (loadRes)
	{
		strTransLocalFile =
				":/" +
				QCoreApplication::applicationName()+"_"+
				QLocale::system().name()+".qm";
		if (appTranslator.load(strTransLocalFile ))
			app.installTranslator(&appTranslator);
	}

	osm_frame_widget w;
	w.show();

	bool taskBusMod = false;
	if(args.contains("instance"))
	{
		stdio = false;
		stdio_box = false;
		taskBusMod = true;
		w.turn_on_taskBus(&args);
	}

	w.show_stdio_checkbox(stdio_box);
	w.turn_on_stdio(stdio);

	//read cmd from stdin
	listen_thread * thread = new listen_thread(&args,taskBusMod);

	thread->connect(thread,&listen_thread::newCmd,&w,
					&osm_frame_widget::slot_call_function,
					Qt::QueuedConnection);
	thread->start();
	ret = app.exec();

	thread->terminate();
	thread->deleteLater();

	return ret;
}
